﻿using System;
using System.IO;
using KeyWordSearch.ProcessTree;

namespace KeyWordSearch.DebugHelper
{
	internal static class ProcessDigraphProtter
	{
		[ThreadStatic]
		private static int IdSeed = 0;

		public static void Prot(RootNode root,string path)
		{
			StreamWriter wtr = new StreamWriter(path, false);

			wtr.WriteLine("digraph ast");
			wtr.WriteLine("{");
			wtr.WriteLine("\tnode [shape = record, height = 0.01, fontname=\"ＭＳ ゴシック\",fontsize=10.5];");
			IdSeed = 0;

			wtr.WriteLine("{0} [label = \"{{{1}}}\"];", ++IdSeed, "Root");
			Prot(root, IdSeed, wtr);
			wtr.WriteLine("}");
			wtr.Close();
		}

		private static void Prot(NonTerminalNode node,int parentId, StreamWriter wtr)
		{
			node.Childes.Reset();

			while (node.Childes.Next())
			{
				WriteNode(node.Childes.Current, ++IdSeed, parentId, wtr);

				if (node.Childes.Current is NonTerminalNode)
				{
					Prot((NonTerminalNode)node.Childes.Current, IdSeed, wtr);
				}
			}

		}


		private static void WriteNode(ProcessNode node, int Id, int parentId, StreamWriter wtr)
		{
			if (node is OperatorNotProcess)
			{
				wtr.WriteLine("\t{0} [label=\"{{{1}}}\"];", Id, "!");
				wtr.WriteLine("\t{0}->{1};", parentId, Id);
			}
			else if (node is OperatorShortCuttedAndProcess)
			{
				wtr.WriteLine("\t{0} [label=\"{{{1}}}\"];", Id, "&&");
				wtr.WriteLine("\t{0}->{1};", parentId, Id);
			}
			else if (node is OperatorShortCuttedOrProcess)
			{
				wtr.WriteLine("\t{0} [label=\"{{{1}}}\"];", Id, "\\|\\|");
				wtr.WriteLine("\t{0}->{1};", parentId, Id);
			}
			else if (node is ContainCheckProcess)
			{
				ContainCheckProcess proc = (ContainCheckProcess)node;

				wtr.WriteLine("\t{0} [label=\"{{{1}|{2}|{3}|{4}}}\"];", Id, "contain", proc.CheckPhrase.Replace("\"","\\\""), proc.Field, proc.Target);
				wtr.WriteLine("\t{0}->{1};", parentId, Id);
			}
		}
	}
}
